import 'package:built_collection/built_collection.dart';
import 'package:flutter/material.dart';
import 'package:mobile_app.core/core/domain/entities/learning_content/lexical_item/lexical_item.dart';
import 'package:mobile_app.core/core/presentation/helpers/screen_util_mixin.dart';
import 'package:mobile_app.core/core/presentation/theme/theme.dart';
import 'package:mobile_app.core/core/presentation/widgets/app_icon_button.dart';
import 'package:mobile_app.core/core/presentation/widgets/platform_divider.dart';
import 'package:mobile_app.home.core/core/presentation/localization/translation.dart';
import 'package:mobile_app.home.core/core/presentation/theme/home_core_theme.dart';

class UseCaseView extends StatelessWidget with ScreenUtilMixin {
  const UseCaseView({
    required this.useCases,
    required this.pronounceable,
    required this.showExample,
    required this.showTranslation,
    this.showDivider = false,
    this.onUseCasePronunciationButtonPressed,
    super.key,
  })  : assert(useCases.length > 0),
        assert(showExample || showTranslation),
        assert(showExample || !pronounceable),
        assert(!pronounceable || onUseCasePronunciationButtonPressed != null);

  final BuiltList<LexicalItemUseCase> useCases;
  final bool pronounceable;
  final bool showExample;
  final bool showTranslation;
  final bool showDivider;
  final void Function(LexicalItemUseCase)? onUseCasePronunciationButtonPressed;

  double get _scaleFactor => logWidthScaleFactor;

  VoidCallback? _buildOnUseCasePronunciationButtonPressedCallback({
    required LexicalItemUseCase useCase,
  }) {
    if (onUseCasePronunciationButtonPressed != null) {
      return () {
        onUseCasePronunciationButtonPressed!.call(useCase);
      };
    }

    return null;
  }

  Widget _buildUseCases({
    required BuildContext context,
  }) {
    final double gapHeight;
    if (showTranslation && showExample) {
      gapHeight = 26 * _scaleFactor;
    } else {
      gapHeight = 18 * _scaleFactor;
    }

    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: useCases.length,
      itemBuilder: (context, index) {
        return _SingleUseCaseView(
          useCase: useCases[index],
          pronounceable: pronounceable,
          showExample: showExample,
          showTranslation: showTranslation,
          onPronunciationButtonPressed: _buildOnUseCasePronunciationButtonPressedCallback(
            useCase: useCases[index],
          ),
        );
      },
      separatorBuilder: (context, index) {
        return SizedBox(
          height: gapHeight,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (showDivider)
          const Padding(
            padding: EdgeInsets.only(top: 2),
            child: PlatformDivider(),
          ),
        Padding(
          padding: EdgeInsets.symmetric(
            vertical: 30 * _scaleFactor,
            horizontal: 50 * _scaleFactor,
          ),
          child: Text(
            HomeCoreTranslation.of(context).cardUseCaseViewTitle,
            style: HomeCoreTheme.of(context).textTheme.cardUseCaseViewTitle,
            textAlign: TextAlign.center,
            textScaleFactor: _scaleFactor,
          ),
        ),
        _buildUseCases(
          context: context,
        ),
        SizedBox(
          height: 30 * _scaleFactor,
        ),
      ],
    );
  }
}

class _SingleUseCaseView extends StatelessWidget with ScreenUtilMixin {
  const _SingleUseCaseView({
    required this.useCase,
    required this.pronounceable,
    required this.showExample,
    required this.showTranslation,
    this.onPronunciationButtonPressed,
  })  : assert(showExample || showTranslation),
        assert(showExample || !pronounceable),
        assert(!pronounceable || onPronunciationButtonPressed != null);

  static const _leadingWidth = 50.0;

  final LexicalItemUseCase useCase;
  final bool pronounceable;
  final bool showExample;
  final bool showTranslation;
  final VoidCallback? onPronunciationButtonPressed;

  double get _scaleFactor => logWidthScaleFactor;

  Widget _buildUseCaseText({
    required BuildContext context,
    required String text,
    required FontStyle fontStyle,
  }) {
    final parts = text.split('#');

    final partTextSpans = <TextSpan>[];

    for (var i = 0; i < parts.length; i++) {
      late final TextSpan textSpan;
      if (i.isEven) {
        textSpan = TextSpan(text: parts[i]);
      } else {
        textSpan = TextSpan(
          text: parts[i],
          style: HomeCoreTheme.of(context).textTheme.cardLexicalItemBoldUseCase.copyWith(
                fontStyle: fontStyle,
              ),
        );
      }
      partTextSpans.add(textSpan);
    }

    return Text.rich(
      TextSpan(
        style: HomeCoreTheme.of(context).textTheme.cardLexicalItemUseCase.copyWith(
              fontStyle: fontStyle,
            ),
        children: partTextSpans,
      ),
      textScaleFactor: _scaleFactor,
    );
  }

  Widget _buildUseCaseTranslation({
    required BuildContext context,
  }) {
    return _buildUseCaseText(
      context: context,
      text: useCase.translationMarkdown,
      fontStyle: showExample ? FontStyle.italic : FontStyle.normal,
    );
  }

  Widget _buildUseCaseExample({
    required BuildContext context,
  }) {
    return _buildUseCaseText(
      context: context,
      text: useCase.exampleMarkdown,
      fontStyle: FontStyle.normal,
    );
  }

  @override
  Widget build(BuildContext context) {
    late final Widget topRow;
    Widget? bottomRow;
    Widget topRowLeading;

    if (pronounceable) {
      topRowLeading = AppIconButton(
        width: _leadingWidth * _scaleFactor,
        height: 32 * _scaleFactor,
        icon: Icon(
          Icons.volume_up_rounded,
          size: 26 * _scaleFactor,
          color: CoreTheme.of(context).primaryColor,
        ),
        onPressed: onPronunciationButtonPressed!,
      );
    } else {
      topRowLeading = SizedBox(
        width: _leadingWidth * _scaleFactor,
        child: Center(
          child: Icon(
            Icons.star,
            size: 20 * _scaleFactor,
            color: CoreTheme.of(context).primaryColor,
          ),
        ),
      );
    }

    if (showExample && showTranslation) {
      topRow = Row(
        children: [
          topRowLeading,
          Expanded(
            child: _buildUseCaseExample(
              context: context,
            ),
          ),
        ],
      );

      bottomRow = Row(
        children: [
          SizedBox(
            width: _leadingWidth * _scaleFactor,
          ),
          Expanded(
            child: _buildUseCaseTranslation(
              context: context,
            ),
          ),
        ],
      );
    } else if (showExample) {
      topRow = Row(
        children: [
          topRowLeading,
          Expanded(
            child: _buildUseCaseExample(
              context: context,
            ),
          ),
        ],
      );
    } else if (showTranslation) {
      topRow = Row(
        children: [
          topRowLeading,
          Expanded(
            child: _buildUseCaseTranslation(
              context: context,
            ),
          ),
        ],
      );
    }

    return Padding(
      padding: EdgeInsets.only(
        right: 16 * _scaleFactor,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          topRow,
          if (bottomRow != null)
            Padding(
              padding: EdgeInsets.only(
                top: 6 * _scaleFactor,
              ),
              child: bottomRow,
            ),
        ],
      ),
    );
  }
}
